<?php

$err = 0;
$warn = 0;
ini_set('max_execution_time', 0);
@set_time_limit(0);
ini_set('auto_detect_line_endings', 1);
@ini_set('display_errors', 1);
//restore_include_path();
session_start();
if ($_GET['restart'])
{
    unset($_SESSION['ini']);
    header("Location: index.html");
    exit;
}
/*
* mysql < dump.sql
*/
function file_to_db($filename)
{
    if (!$lines = file($filename))
    {
        echo "<div class=err>ERROR: can not read $filename</div>";
        return 0;
    }
    foreach ($lines as $l)
    {
        if (preg_match("/^\s*(#|--)/", $l))
        {
            //do no
        } else
            if (preg_match("/;\s*$/", $l))
            {
                $query = $query . substr($l, 0, -1);

                if (!mysql_query($query))
                {
                    echo "<div class=err>ERROR: cannot execute database query</div>
	 <pre>
	 $query
	 </pre>";
                    return 0;
                }
                $query = '';
            } else
            {
                $query = $query . $l;
            }
    }
    return 1;
}
?>
<html>
<head>
<title>phpMyTicket installation</title>
<link rel="stylesheet" href="http://www.phpmyticket.com/spip/style.css" type="text/css">
<style>
  .err {color:#dd0000;}
  .warn {color:#cc9900;}
  .ok {color:#00dd00;}
</style>
</head>
<body>

<?

if ($_POST['install'] and $_POST['inst_button'])
{
    echo '<table width=500><tr><td>';
    $install_dir = $_SESSION['ini']['install_dir'];
    $includes_dir = $install_dir . "/includes";
    if (!$init_common = file_get_contents("$install_dir/inst/init_common.php"))
   {
        echo "<div class='err'>Cannot read configuration file <i>
		$install_dir/inst/init_common.php</i></div>";
        exit;
    } else
    {
        function callback($matches)
        {
            return $_SESSION['ini'][$matches[1]];
        }

        $_SESSION['ini']['install_dir_esc'] = addslashes($_SESSION['ini']['install_dir']);
        $_SESSION['ini']['full_include_path'] = get_include_path() . PATH_SEPARATOR . $_SESSION['ini']['install_dir'];
        if ($_SESSION['ini']['install_mode'] == 'install')
        {
            $_SESSION['ini']['old_organizer_id'] = 3;
        }
        $init_common = preg_replace_callback("/%(\w+)%/", "callback", $init_common);
        if (!$fh = fopen("$includes_dir/config/init_common.php", 'w') or !fwrite($fh, $init_common) or
            !fclose($fh))
        {
            echo "<div class=err>Can not write configuration file $includes_dir/config/init_common.php</div>";
            exit;
        }
    }
    //with SAFEMODE: delete the following "IF"
    //after install create those folders by hand
    //set access rights to 777
    //delete from here->
    if (!mkdir("$includes_dir/tmp/web") or !mkdir("$includes_dir/tmp/web/templates_c") or
        !mkdir("$includes_dir/tmp/web/cache") or !mkdir("$includes_dir/tmp/pos") or !
        mkdir("$includes_dir/tmp/pos/templates_c") or !mkdir("$includes_dir/tmp/pos/cache"))
    {
        echo "<div class=warn>WARNING: can not create temporary folders under 
                           $includes_dir/tmp</div>";
        $warn++;
    }
    //<-to here
    if (!(mysql_connect($_SESSION['ini']['db_host'], $_SESSION['ini']['db_uname'], $_SESSION['ini']['db_pass']) and
        mysql_select_db($_SESSION['ini']['db_name'])))
    {
        echo "<div class=err>ERROR: can not connect to the database</div>";
        exit;
    }

    if ($_SESSION['ini']['install_mode'] == 'install')
    {

        //import contens of mysqldump to db

        if (file_to_db("$install_dir/inst/phpMyTicket.sql"))
        {

            echo "<div class=ok>Database structure created</div>";

        } else
        {

            echo "<div class=err>ERROR: can not create database structure!</div>";

            exit;

        }

        //create admin user

        $query = "update Admin set

						 admin_login='{$_SESSION['ini']['admin_login']}',

						 admin_password=md5('{$_SESSION['ini']['admin_password']}')

						 where

						 admin_id='3' and

						 admin_status='organizer'";

        if (mysql_query($query))
        {

            echo "<div class=ok>Admin user created</div>";

        } else
        {

            echo "<div class=err>ERROR: Admin user can not be created!</div>";

            exit;

        }

        //force recompile of templates

        $query = "UPDATE Template set template_status='new'";

        mysql_query($query);

        //because of a bug on my mac!

        $query = "ALTER TABLE `order` RENAME `Order`";

        mysql_query($query);

    } else
        if ($_SESSION['ini']['install_mode'] == 'update')
        {

            //force recompile of templates

            $query = "UPDATE Template set template_status='new'";

            mysql_query($query);

        }

    if (!$err)
    {

        if (!$warn)
        {

            echo "<h1 class=ok>phpMyTicket was successfully installed</h1><hr><br>";

        } else
        {

            echo "<h1 class=warn>phpMyTicket was parially installed, with warnings!</h1><hr>

			Maybe it will not work!!! 

			<br>";

        }

        if ($_SESSION['ini']['install_mode'] == 'update')
        {

            echo "<b>Attention!</b> If you have modified original smarty templates, 

			you will need to move and adapt them. You also need to re-upload all images ans mp3 files.";

        } else
        {

            echo "<b>Attention</b> Demo users was created for control and salepoint interfaces with login <i>demo</i>

			, password <i>demodemo</i>. <b>Please change those passwords in admin interface!!!</b>";

        }

        echo "

<div>For the security reasons you should put this file to read-only by webserver: <br>

<br> <tt>includes/config/init_common.php</tt></div>

<div>You also have to delete the <tt>inst</tt> folder.</div>

<br><br>     



<li><a href='../admin/index.php' target='_blank'>Go to Admin</a>. <br>

<li><a href='../index.php' target='_blank'>Go to Demo Shop</a> <br>

<li><a href='../pos/index.php' target='_blank'>Go to Demo Sale Point</a><br>

<li><a href='../control/index.php' target='_blank'>Go to Demo Ticket Control Point</a><br>





<br><br>

Please, say us if you run phpmyticket on your site : 

add your site to <a href='http://www.phpmyticket.com/en/live.html' target='_new'>'Live Sites'</a> page or

send us an email to <i>info at phpmyticket dot com</i> !

<br><br>

";

        session_destroy();

        exit;

    } else
    {

        echo "<h1 class=err>phpMyTicket installation failed</h1><hr>

            <a href=''>Change parameters and try again?</a>";

        exit;

    }

    echo "</td></tr></table>";

} else
    if ($_POST['back_button'])
    {

        unset($_SESSION['ini']);

    }



?>

<h1 class="titre-texte">Welcome to phpMyTicket installation script!</h1>

<table width=500><tr><td>



<?



//chechk php version

if (!$_SESSION['ini']['php_version'])
{
    $ver = explode('.', phpversion());
    if ($ver[0] != 5)
    {
        echo "<li><span class='err'>FAILED: php version 5 is required, You have php version " .
        phpversion() . "</span></li>";
        $err++;
    } else
        if ($ver[1] < 2 or $ver[2] < 5)
        {
            echo "<li><span class='warn'>WARNING: this program was tested with php version 5.2.5 or more. You have php version " .phpversion() . ". Probably this is not a problem.</span ></li>";
            $warn++;
        } else
        {
            echo "<div class=ok>php version is OK</div>";
            $_SESSION['ini']['php_version'] = 1;
        }
}
if (!function_exists('curl_init'))
{
    echo "<li><span class='warn'>WARNING: <a href='http://ch2.php.net/manual/en/ref.curl.php'>cURL</a> is not compiled in your php. cURL is used by paypal or authorize.net payment methods - you will be unable to use those. Install curl, or configure another network library in <i>'includes/config/init_common.php'</i></span ></li>";
    $warn++;
}
if (!function_exists('iconv'))
{
    echo "<li><span class='warn'>WARNING: <a href='http://ch2.php.net/manual/en/ref.iconv.php'>iconv</a> is not compiled in your php. iconv is used to enable non-latin alphabets in PDF templates.</span ></li>";
    $warn++;
}
if (!function_exists('xml_parser_create'))
{
    echo "<li><span class='warn'>WARNING: <a href='http://ch2.php.net/manual/en/ref.xml.php'>xml parser</a> is not compiled in your php. xml parser is used by email and pdf templates - you will be unable to print tickets and send emails</span ></li>";
    $warn++;
}

if (!function_exists('openssl_seal'))
{
    echo "<li><span class='warn'>WARNING: <a href='http://ch2.php.net/manual/en/ref.openssl.php'>openssl</a> is not compiled in your php. openssl is used to encrypt credit card information - you will be unable to use this feature.</span ></li>";
    $warn++;
}
if (ini_get('register_globals'))
{
    echo "<li><span class='warn'>WARNING: For security reasons 'register_globals' should be 'OFF'. Read documentation for explanations.</span ></li>";
    $warn++;
}

if (ini_get('safe_mode'))
{
    echo "<li><span class='warn'>WARNING: Your php is in 'SAFE MODE'. This can lead to problems during install (unable to create directory errors). Please read documentation.</span ></li>";

    $warn++;
}



?>



<form action="" method="post">
<h4>New Install or Update?</h4>
Please choose if this is a new install or an update <b>from phpMyTicket-0.3.2</b>.
If you choose the update you should provide valid access parameters to your existing database.
Your current database will be reused<br>
<li><b>NB 1</b> Update is only possible from v.0.3.2<br>

<?
if ($_POST['install_mode'])
{
    $_SESSION['ini']['install_mode'] = $_POST['install_mode'];
}
if (!$install_mode = $_SESSION['ini']['install_mode'])
{
    $install_mode = 'install';
}
$chk[$install_mode] = 'checked';
echo "
<label><input type='radio' name='install_mode' value='install' " . $chk['install'] .
    "> New installation</label><br>";
//<label><input type='radio' name='install_mode' value='update' " . $chk['update'] .
//    "> Update from v.0.3.2</label><br>";

?>

<h4>Main directory</h4>
There is the directory where phpMyAdmin is installed. Fix if incorrect:<br>

<?
if ($_POST['install_dir'])
{
    $_SESSION['ini']['install_dir'] = $_POST['install_dir'];
}

if (!$install_dir = $_SESSION['ini']['install_dir'])
{
    $cwd = getcwd();
    $install_dir = substr($cwd, 0, -5);
}

echo "<input name='install_dir' value='$install_dir' size='50'>";
if (!is_writable("$install_dir/includes/config/init_common.php"))
{
    echo "<div class=err>$install_dir/includes/config/init_common.php should be writable by the webserver user.</div> Please change the permissions of this file<br>";
    $err++;
}

if (!is_writable("$install_dir/includes/fonts"))
{
    echo "<div class=err>$install_dir/includes/fonts should be writable by the webserver user.</div> Please change the permissions of this directory<br>";
    $err++;
}

if (!file_exists("$install_dir/includes/tmp") and is_writable($install_dir .
    "/includes") and mkdir("$install_dir/includes/tmp"))
{
    //thats ok
} else
    if (!is_writable("$install_dir/includes/tmp"))
    {
        echo "<div class=err>$install_dir/includes/tmp should be writable by the webserver user.</div> Please change the permissions of this directory<br>";
        $err++;
    }
if (!file_exists("$install_dir/files") and is_writable($install_dir) and mkdir("$install_dir/files"))
{
    //thats ok
} else
    if (!is_writable("$install_dir/files"))
    {
        echo "<div class=err>$install_dir/files should be writable by the webserver user.</div> Please change the permissions of this directory<br>";
        $err++;
    }
?>



<h4>Base URL</h4>
This is the URL of phpMyTicket files. Fix if incorrect:<br>
<?

if ($_POST['root'])
{
    $_SESSION['ini']['root'] = $_POST['root'];
}

if (!$root = $_SESSION['ini']['root'])
{
    $root = "http://" . $_SERVER['HTTP_HOST'];
    $root .= substr($_SERVER['SCRIPT_NAME'], 0, -16);
}
echo "<input name='root' value='$root' size='50'>";

?>


<h4>Database connection</h4>
In order to run phpMyTicket a database should be created. 
Please create the database and provide access parameters here. For the update: 
please provide parameters of existing phpMyTicket database.
<table>

<?
if ($_POST['db_host'])
{
    $_SESSION['ini']['db_host'] = $_POST['db_host'];
}
if ($_POST['db_name'])
{
    $_SESSION['ini']['db_name'] = $_POST['db_name'];
}
if ($_POST['db_uname'])
{
    $_SESSION['ini']['db_uname'] = $_POST['db_uname'];
}
if ($_POST['db_pass'])
{
    $_SESSION['ini']['db_pass'] = $_POST['db_pass'];
}

if (!$_SESSION['ini']['db_host'])
{
    $db_host = 'localhost';
} else
{
    $db_host = $_SESSION['ini']['db_host'];
}
echo "
<tr><td>Database host</td><td><input type=text name='db_host' value='$db_host'></td></tr>
<tr><td>Database name</td><td><input type=text name='db_name' value='{$_SESSION['ini']['db_name']}'></td></tr>
<tr><td>Database user name</td><td><input type=text name='db_uname' value='{$_SESSION['ini']['db_uname']}'></td></tr>
<tr><td>Database password</td><td><input type=text name='db_pass' value='{$_SESSION['ini']['db_pass']}'></td></tr>
</table>";
if ($_SESSION['ini']['db_host'] and $_SESSION['ini']['db_uname'] and $_SESSION['ini']['db_name'])
{
    if ($db = mysql_connect($_SESSION['ini']['db_host'], $_SESSION['ini']['db_uname'],
        $_SESSION['ini']['db_pass']))
    {
        if (mysql_select_db($_SESSION['ini']['db_name'])){
            echo "<div class='ok'>Database connection verified OK</div>";
                if ($install_mode == 'install')
                {
                    if ($res = mysql_list_tables($_SESSION['ini']['db_name']) and mysql_fetch_row($res))
                    {
                        echo "<div class=err>ERROR: Selected database {$_SESSION['ini']['db_name']} is <b>not empty</b>!</div>";
                        $err++;
                    }
                }
                if ($install_mode == 'update'){
                    if ($res = mysql_list_tables($_SESSION['ini']['db_name']) and !mysql_fetch_row($res))
                    {
                        echo "<div class=err>ERROR: Selected database {$_SESSION['ini']['db_name']} is <b>empty</b>!</div>";
                        $err++;
                    }
                }
        }else{
            echo "<div class='err'>Database server connection OK, but cannot use specified database</div>";
            $err++;
        }
    } else
    {
        echo "<div class='err'>Database server connection FAILED</div>";
        $err++;
    }
} else
{
    $err++;
}
if ($_SESSION['ini']['install_mode'] == 'install')
{
?>



	<h4>Admin login and password</h4>

	

	Please choose the username and the password for the phpMyTicket super user<br>

  (Choose it even if you update, this will be your new login / password )<br>	

	<table>

	

	<?



    if ($_POST['admin_login'])
    {

        $_SESSION['ini']['admin_login'] = $_POST['admin_login'];

    }

    if ($_POST['admin_password'])
    {

        $_SESSION['ini']['admin_password'] = $_POST['admin_password'];

    }

    echo "

	<tr><td>Admin login</td><td><input type=text name='admin_login' value='{$_SESSION['ini']['admin_login']}'></td></tr>

	<tr><td>Admin password (at least 6 letters)</td><td><input type=text name='admin_password' value='{$_SESSION['ini']['admin_password']}'></td></tr>

	</table>

	";

    if (isset($_SESSION['ini']['admin_login']) and isset($_SESSION['ini']['admin_password']))
    {

        if (strlen($_SESSION['ini']['admin_login']) == 0)
        {

            echo "<div class=err>Please choose admin login</div>";

            $err++;

        }

        if (strlen($_SESSION['ini']['admin_password']) < 6)
        {

            echo "<div class=err>Admin password should be at least 6 letters long</div>";

            $err++;

        }

    } else
    {

        $err++;

    }

}

?>



<hr>

<?

if ($err)
{

    echo "<div class=warn>Please provide missing values and fix errors.</div>";

    echo "<input type='submit' value='Continue'>";

    echo "<input type='reset' value='Reset'>";

} else
{

    echo "<div class=ok>You are ready to install! Do not change anything more!</div>";

    echo "<input type=hidden name=install value=1>";

    echo "<input type='submit' name='inst_button' value='Install it now'>";

    echo "<div>If you need to change some parameters type 'Go Back' instead.</div>";

    echo "<input type='submit' name='back_button' value='Go back'>";

}

?>

</form>

<a href='?restart=1'>restart install</a>

</td></tr></table>

</body>

</html>

